import logging
import os
import sys
import time
from colorama import init, Fore, Style
# 程序启动时间
START_TIME = time.time()

# 日志配置
_logger = logging.getLogger("simple_logger")
_logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)


class ColorFormatter(logging.Formatter):
    COLORS = {
        logging.DEBUG: Fore.GREEN,
        logging.INFO: Fore.WHITE,
        logging.WARNING: Fore.YELLOW,
        logging.ERROR: Fore.RED,
        logging.CRITICAL: Fore.MAGENTA,
    }

    def format(self, record):
        color = self.COLORS.get(record.levelno, "")
        record.msg = f"{color}{record.msg}{Style.RESET_ALL}"
        elapsed_ms = time.time() - START_TIME
        record.elapsed = f"{elapsed_ms:8.3f}"
        record.levelname = f"{record.levelname:<5}"

        # 添加文件名和行号信息
        filename = os.path.basename(record.pathname)
        record.location = f"{filename}:{record.lineno}"
        return super().format(record)


formatter = ColorFormatter("[%(elapsed)s] [%(levelname)s] [%(location)-20s] %(message)s")
ch.setFormatter(formatter)
_logger.addHandler(ch)


# 日志函数 - 添加额外的调用栈信息
def debug(msg):    _logger.debug(msg, stacklevel=2)


def info(msg):     _logger.info(msg, stacklevel=2)


def warning(msg):  _logger.warning(msg, stacklevel=2)


def error(msg):    _logger.error(msg, stacklevel=2)


def critical(msg): _logger.critical(msg, stacklevel=2)